define(function (require, exports, module) {

    require("apps/grid");
    require("apps/easyui");

    function formatDate (date) {
        var year = date.getFullYear();
        var month = addZero(date.getMonth() + 1);
        var day = addZero(date.getDate());
        //var hour = addZero(date.getHours());
        //var min = addZero(date.getMinutes());
        //var sec = addZero(date.getSeconds());
        return year+"-"+month+"-"+day;//+" "+hour+":"+min/*+":"+sec*/;
    };

    function addZero(number){
        return number > 9 ? number + "" : "0" + number;
    }

    function convertSlotIndexToTimeString(index){
        var baseTime = new Date();
        var time = new Date(
            baseTime.getFullYear(),
            baseTime.getMonth(),
            baseTime.getDate(),
            8 + (30 * index) / 60,
            index % 2 == 0 ? 0 : 30,
            0
        );
        return time.format("hh:mm");
    }

    function calculateMeetingEndDateTime(date, beginTimeIndex, slotCount) {
        var endIndex = beginTimeIndex + slotCount;
        var hour = 8 + (30 * endIndex) / 60;
        var minutes = endIndex % 2 == 0 ? 0 : 30;

        date.setHours(hour);
        date.setMinutes(minutes);
        date.setMilliseconds(0);

        return date;
    }

    function createColumns(startIndex, endIndex) {
        var columns = [];
        for (var i = startIndex; i <= endIndex; i++ )
        {
            var oneColumn = {};
            oneColumn.field = "slot" + i;

            var baseTime = new Date();
            var beginTime = new Date(
                baseTime.getFullYear(),
                baseTime.getMonth(),
                baseTime.getDate(),
                8 + (30 * i) / 60,
                i % 2 == 0 ? 0 : 30,
                0
                );
            var beginTimeString = beginTime.format("hh:mm");
            var endTime = new Date(
                baseTime.getFullYear(),
                baseTime.getMonth(),
                baseTime.getDate(),
                8 + (30 * i + 30) / 60,
                i % 2 == 0 ? 30 : 0,
                0
            );
            var endTimeString = endTime.format("hh:mm");

            oneColumn.title = beginTimeString + "-" + endTimeString;
            oneColumn.width = "12%";

            columns.push(oneColumn);
        }

        return columns;
    }

    exports.init = function (ctx, uuid, config) {
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid-meetingList",
                myToolbar: "",
                colbar: "meeting_operation_tempate"
            },
            configs: {
                gridUrl: ctx + '/app/api/meeting/reservation/list',
                gridColumns: [
                    {
                        field: 'date',
                        title: '日期',
                        width: 100,
                        align: 'center'
                    },
                    {
                        field: 'beginTimeIndex',
                        title: '开始时间',
                        width: 100,
                        align: 'center',
                        formatter: function(value, row, index) {
                            return convertSlotIndexToTimeString(value);
                        }
                    },
                    {
                        field: 'slotCount',
                        title: '时长(min)',
                        width: 50,
                        align: 'center',
                        formatter: function(value, row, index){
                            return value * 30;
                        }
                    },
                    {
                        field: 'meetingSubject',
                        title: '会议主题',
                        width: 100,
                        align: 'center'
                    },
                    {
                        field: 'reserveUser.userName',
                        title: '预约人',
                        width: 50,
                        align: 'center'
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        width: 160,
                        align: 'center'
                    }
                ],
                onLoadSuccess: function(data) {
                    $('#table-timeslots tr:eq(1) td').text("").removeClass("reserved");
                    if (data.total > 0) {
                        var meetings = data.rows;
                        var length = meetings.length;
                        for(var i = 0; i < length; i++) {
                            var meeting = meetings[i];
                            for (var j = 0; j< meeting.slotCount; j++)
                            {
                                var index = meeting.beginTimeIndex + j;
                                $('#table-timeslots tr:eq(1) td:eq('+ index +')').text(meeting.reserveUser.userName).addClass("reserved");
                            }
                        }
                    }

                }
            },
            events: {
                renderColBarBefore: function (type, row) {
                    // user can only delete meeting that he/she created.
                    if (row.reserveUser.id == config.loginUserId) {

                        // if the meeting has ended, do not allow deletion
                        var meetingDateTime = calculateMeetingEndDateTime(new Date(row.date), row.beginTimeIndex, row.slotCount);
                        if (meetingDateTime > new Date()) {
                            return true;
                        }
                    }
                    return false;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "del":
                            whenDelete(context, btn.href, row.id);
                            break;
                        default:
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                }
            }
        });

        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("meeting-remark").val(""); // there is a small bug that cursor doesn't align to left when first load
        page.getJqDom("meeting-date").datebox({
            onSelect: function(date){
                page.getJqDom("grid-meetingList").datagrid("load", {
                    date: date.format("yyyy-MM-dd")
                });

                if (date.format("yyyy-MM-dd") < new Date().format("yyyy-MM-dd")) {
                    // disable add meeting
                    page.getJqDom("next").linkbutton("disable");
                } else {
                    page.getJqDom("next").linkbutton("enable");
                }
            }
        });

        page.getJqDom("meeting-date").datebox('setValue', formatDate(new Date()));
        page.getJqDom("form-meeting-add-reservation").find(".easyui-validatebox").validatebox();

        page.getJqDom("next").linkbutton({
            onClick: function () {
                var postForm = page.getJqDom("form-meeting-add-reservation");
                if (!postForm.form('validate')) {
                    return false;
                }

                var postData = postForm.serializeJson();

                var time = calculateMeetingEndDateTime(new Date(postData.date), postData.beginTimeIndex, postData.slotCount);
                if (time.getTime() < new Date().getTime()) {
                    $.messager.alert('Error', '会议时间已经过期，请选择正确的结束时间。', 'info');
                    return false;
                }

                $("body").wait("start", "保存中,请稍候.");
                $.post(postForm.attr("action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                    function (json) {
                        $("body").wait("end");
                        if ($.utils.isError(json)) {
                            $.messager.alert('Error', json.msg, 'info');
                        } else {
                            if (json.isConflict == "true") {
                                $.messager.alert('Error', '会议时间冲突，请选择其它时间段。', 'info');
                            } else {
                                $.messager.alert('信息', '保存成功', 'info');
                                // reload table and reset form data to default value
                                page.getJqDom("grid-meetingList").datagrid("reload");
                            }
                        }
                    }, "json");
            }
        });

        var contextWindow = new $.PageWindow();

        function whenDelete(context, href, id) {
            $.messager.confirm('确定','确定要取消会议吗？',function(result){
                if(result) {
                    var postData = {};
                    postData.id = id;

                    $.post(href,
                        $.utils.buildJson(postData),
                        function (json) {
                        if ($.isErrorRequest(json)) {
                            $.messager.alert('信息', json.msg, 'info');
                        } else {
                            page.getJqDom("grid-meetingList").datagrid("reload");
                            $.messager.alert('信息', '取消成功', 'info');
                        }
                        });
                }
            } );
        }
    }
});
